Skip to content


ai  101  pytorch  classification  nvidia  cuda  install  tensorrt  yolo  ardupilot  None  ros2  dds  micro ros  xrce  sitl  plugin  SITL  debug  rangefinder  pymavlink  mavros  gazebo  distance sensor  system_time  timesync  cmake  gtest  ctest  cpp  c++  format  fmt  multithreading  spdlog  camera  coordinate system  orb  matching  opencv  build  transformation  computer vision  homography  optical flow  of  trackers  cv  cyclonedds  eprosima  fastdds  simulation  config  ignition  bridge  sdf  tips  ign-transport  sensors  lidar  aptly  apt  encryption  pgp  docker  git  bundle  github  hooks  pre-commit  lxd  container  lxc  x11  profile  vscode  marpit  presentation  marp  markdown  mermaid  video  ffmpeg  gstreamer  cheat-sheet  sdp  v4l2loopback  gi  snippets  cheat Sheet  python  asyncio  future  click  cli  numpy  project  template  black  isort  docs  project document  docstrings  flake8  linter  git-hook  mypy  unittest  pytest  pylint  mock  iterator  generator  logging  tuple  namedtuple  typing  annotation  pyzmq  zmq  msgpack  action  namespace  remap  control2  ros2_control  gdb  qos  tag  plugins  msg  node  zero-copy  shm  tutorial  algorithm  calibration  diff  pid  dev  colcon  colcon_cd  rpi  arm  qemu  settings  behavior  plot  visualization  debugging  diagnostic  diagnostics  tutorials  gst  math  apm  rat_runtime_monitor  web  rosbridge  vue  binding  discovery  gazebo-classic  launch  spawn  cook  gps  imu  ray  gazebo_ros_ray_sensor  ultrsonic  range  ultrasonic  gazebo classic  wrench  effort  odom  ign  gz  xacro  ros_ign  diff_drive  odometry  joint_state  argument  OpaqueFunction  DeclareLaunchArgument  LaunchConfiguration  tmux  nav  slam  test  rclpy  executor  MultiThreadedExecutor  SingleThreadedExecutor  param  dynamic-reconfigure  service  client  setup.py  package.xml  parameter  parameters  custom  msgs  executers  pub  sub  rqt  rviz  rviz2  pose  marker  tf2  deb  package  setup  local_setup  rosdep  package manager  project settings  vcstool  cross-compiler  nano  texture  tmuxp  rootfs  embedded  zah  linux  rm  ubuntu  ip  ss  network  netstat  snap  deploy  ssh  systemd  mkdocs  extensions  socat  networking  serial  udp  tc  mtu  select  px4  robotics  kalman_filter  kalman  filter  control  todo  vscode-ext  json  yaml  schema  yocto  poky  world  gazebo_ros2_control  position_controller  effort_controller  velocity_controller  urdf  gazebo_ros_force  gazebo_ros_joint_state_publisher  robot_state_publisher  joint_state_publisher  projects  vrx  buoyancy 

Iterator in Python is simply an object that can be iterated upon. An object which will return data, one element at a time.

Python iterator object must implement two special methods (iterator protocol) - iter() - next()

iterable

An object is called iterable if we can get an iterator from it. Container like list and tuple are iterable object


Custom iterators#

class Base2():
    def __init__(self, max) -> None:
        self.__max = max
        self.__current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.__current > self.__max:
            raise StopIteration()
        result = 2**self.__current
        self.__current += 1
        return result

iter and next

iter(obj) and next(obj) method is the same like calling obj.__next__() and obj.__iter__() method

iterator usage#

  • Iterator raise StopIteration exception when it’s ended
worker = Base2(2)
worker_iter = worker.__iter__()
print(next(worker_iter))
print(worker_iter.__next__())
print(next(worker_iter))
print(next(worker_iter))

1
2
4
Traceback (most recent call last):
  File "/home/user/projects/blog/examples/python/python/custom_iterators.py", line 22, in <module>
    print(next(worker_iter))
  File "/home/user/projects/blog/examples/python/python/custom_iterators.py", line 12, in __next__
    raise StopIteration()
StopIteration

Generator#

def base2(max):
    for x in range(max):
        yield 2**x

print(base2(3))
for i in base2(3):
    print(i)

<generator object base2 at 0x7f8aa5cc07b0>
1
2
4

Generator Expression#

g = (2**x for x in range(3))
print(g)
for i in g:
    print(i)

#
<generator object <genexpr> at 0x7f9af03247b0>
1
2
4

Reference#